﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using plas.core;
using plas.cps.ui.Tools;

namespace plas.cps.ui
{
    public partial class StartForm : Form
    {
        Thread th;
        ApplicationHandler actual;
        private bool exit = false;

        public StartForm(ApplicationHandler actual)
        {
            this.actual = actual;
            InitializeComponent();
        }
        private void StartForm_Load(object sender, EventArgs e)
        {
            if (actual.ApplicationStatus != AppStatus.RUNNING)
            {
                actual.threadEvent += new ApplicationEventHandle(actual_threadEvent);
                actual.threadEndEvent += new ApplicationEventHandle(actual_threadEndEvent);
                actual.threadErrorEvent += new ApplicationEventHandle(actual_threadErrorEvent);

                th = new Thread(new ThreadStart(actual.startUp));
                th.Start();
                this.label1.Visible = true;
                this.progressBar1.Visible = true;
                this.button1.Enabled = false;
            }
            else
            {
                this.button1.Enabled = true;
            }
        }

        void actual_threadErrorEvent(object sender, ApplicationEventArg arg)
        {
            if (!exit)
            {
                MessageBoxUtil.ShowErrorBox("系统初始化失败，请检查系统配置后重试");
                this.Invoke((EventHandler)delegate
               {
                   this.Close();
               });
            }

        }

        void actual_threadEndEvent(object sender, ApplicationEventArg arg)
        {
            this.Invoke((EventHandler)delegate
            {
                this.button1.Enabled = true;
            });
        }

        void actual_threadEvent(object sender, ApplicationEventArg arg)
        {
            this.Invoke((EventHandler)delegate
            {
                this.label1.Text = arg.Message;
                this.progressBar1.Value = arg.Progress;
            });
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            if (th != null && th.ThreadState == ThreadState.Running)
                th.Abort();
            this.exit = true;
            Application.ExitThread();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }


    }
}
